#!/bin/bash

curr_user="$(whoami)"

# yum list installed nginx 查看已安装的 nginx 包。
# Check if Nginx is installed and uninstall it if necessary
if command -v nginx &>/dev/null; then
  echo "Nginx is installed, removing..."
  # Uninstall Nginx
  if sudo yum remove nginx -y; then
    echo "Nginx has been successfully uninstalled."
  else
    echo "Failed to uninstall Nginx."
  fi
else
  echo "Nginx is not installed, nothing to uninstall."
fi

echo "Nginx reinstall ..."
sudo yum install -y nginx && sudo systemctl enable nginx
echo "Nginx has been successfully installed."
yum list installed nginx

echo "改变 /etc/nginx/conf.d 所有者"
sudo chown -R "$curr_user" /etc/nginx/conf.d

echo "创建 ~/app/web 目录，并将目录的组更改为 nginx"
mkdir -p ~/app/web && sudo chown :nginx ~/app/web

sudo gpasswd -a nginx "$curr_user"
chmod g+x ~/app && chmod g+x ~/app/web

echo "测试 nginx 对 ~/app/web 目录是否拥有权限"
sudo -u nginx stat ~/app/web

echo "测试 nginx 对 ~/app 目录是否拥有权限"
sudo -u nginx stat ~/app

# 关闭 selinux 状态
is_disabled=$(grep SELINUX=disabled /etc/selinux/config)
if [ "$is_disabled" == "SELINUX=disabled" ]; then
  sudo bash -c "cat>>/etc/selinux/config" <<EOF
SELINUX=disabled
EOF
  # 重启服务器
  sudo reboot
fi
